import json
import re

import flask
from flask import jsonify, request
from flask_cors import CORS

import MyClass as mc
import BaseFunction as BF
import 搜搜小说网 as ss
import 笔趣阁 as bqg
import 第二课堂 as xbqg

app = flask.Flask(__name__)
app.config["DEBUG"] = True

# 网页正则表达式
rebqg = r'https://www.boquge.com\S'
rexbqg = r'http://www.xbiquge.la\S'
ress = r'https://www.soxs.cc\S'


@app.route('/', methods=['GET'])
def home():
    return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction " \
           "novels.</p> "


@app.route('/api/getuser', methods=['POST'])
def getUser():
    return jsonify("{name:'123',age:12}")


@app.route('/api/search', methods=['GET'])
def Search():
    searchName = request.args.get('name')
    Books = []
    BF.AppendBook(Books, searchName)
    bookList = []
    for bs in Books:
        for book in bs:
            book.href = book.href.split()[0]
            bookList.append(book.__dict__)
    # 最主要的是 href 链接
    return jsonify(bookList)


@app.route('/api/getcharpet')
def getCharpterList():
    href = request.args.get('href').split()[0]
    source = request.args.get('source')
    tempList = []
    sortlist = []
    sections = []
    if source == '笔趣阁':
        tempList = bqg.ZJIndex(href)
    elif source == '新笔趣阁':
        tempList = xbqg.GetChapterList(href)
    elif source == '搜书网':
        tempList = ss.GetChapterList(href)
    # 根据Num对章节进行排序
    sortlist = sorted(tempList, key=lambda c: c.num)
    for s in sortlist:
        s.href = s.href.split()[0]
        sections.append(s.__dict__)
    return jsonify(sections)


@app.route('/api/getbody')
def getBody():
    href = request.args.get('href')
    mainBody = ''
    if re.match(rebqg, href, re.I) is not None:
        mainBody = bqg.GetZW(href)
    elif re.match(rexbqg, href, re.I) is not None:
        mainBody = xbqg.getMainBody(href)
    elif re.match(ress, href, re.I) is not None:
        mainBody = ss.GetZWHaveHtml(href)
    return mainBody


def GetNovel():
    return 12


@app.route('/api/checkupdate', methods=['POST'])
# 根据BID 从数据库获取章节数并比较是否存在更新
def FromBaseGetChapterNumByBidAndCheck():
    bids = json.loads(request.form.get('bids'))
    Chapters = []
    returndata = []
    # 遍历传回的bid
    for bid in bids:
        # haveUpdate----0无需更新 1 有更新  2 失效（无有效章节）
        temp1 = {'BID': bid, 'haveUpdate': 0}
        # 从数据库获取对应id书籍信息
        sqlTxt = '''select b.BID,b.href,COUNT(c.ID)as Num
                from BooksInfo as b,ChapterInfo as c 
                where b.BID=%s and c.BID = %s
                group by b.BID,b.href '''
        tempRows = BF.selectmssql(sqlTxt, (bid, bid), **BF.sqlparms)
        # 没有任何章节
        if len(tempRows) == 0:
            temp1['haveUpdate'] = 2
        else:
            row = tempRows[0]
            # 获取章节信息
            if re.match(rebqg, row['href'], re.I) is not None:
                Chapters = sorted(list(bqg.ZJIndex(row['href'])), key=lambda c: c.num)
            elif re.match(rexbqg, row['href'], re.I) is not None:
                Chapters = sorted(list(xbqg.GetChapterList(row['href'])), key=lambda c: c.num)
            elif re.match(ress, row['href'], re.I) is not None:
                Chapters = sorted(list(ss.GetChapterList(row['href'])), key=lambda c: c.num)
            # 比较是否有更新 有更新 标记
            if len(Chapters) > row['Num']:
                temp1['haveUpdate'] = 1
        returndata.append(temp1)
    return jsonify(returndata)


@app.route('/api/checkUpdate')
def checkUpdate():
    mydata = request.args.get('Bidlist')
    return 12


@app.route('/api/getNewBook', methods=['POST'])
def getNewBook():
    mydata = json.loads(request.form.get('mydata'))
    book = mc.book(mydata['type'], mydata['name'], mydata['author'], mydata['href'], None, mydata['utime'])
    if mydata['source'] == 'bqg':
        book.source = '笔趣阁'
        book.Chapters = bqg.GetBody(bqg.ZJIndex(book.href))
    elif mydata['source'] == 'xbqg':
        book.source = '新笔趣阁'
        book.Chapters = xbqg.GetBody(xbqg.GetChapterList(book.href))
    elif mydata['source'] == 'ss':
        book.source = '搜书网'
        book.Chapters = ss.GetBody(ss.GetChapterList(book.href))
    BF.SaveBookInfo(book)
    BF.Save(book.Chapters, book.ID)
    print('123')
    return 1


CORS(app, resources=r'/*')
app.run(port=10021)
